package com.kapcb.assemble.filter;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;
import java.util.Map;

/**
 * <a>Title: DefaultFilterExecutor </a>
 * <a>Author: Kapcb <a>
 * <a>Description: DefaultFilterExecutor <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/4/18 21:35
 * @since 1.0
 */
public class DefaultFilterExecutor extends AbstractFilterExecutor implements ApplicationContextAware, SmartInitializingSingleton {

    private ApplicationContext applicationContext;

    private Map<String, List<Filter>> beanMap = Maps.newConcurrentMap();

    @Override
    protected List<Filter> selectFilter(String type) {
        return null;
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, Filter> filterBeansMap = this.applicationContext.getBeansOfType(Filter.class);
        if (MapUtils.isEmpty(filterBeansMap)) {
            return;
        }

        filterBeansMap.forEach((key, filter) -> {
            List<Filter> filters = beanMap.get(filter.type());
            if (CollectionUtils.isEmpty(filters)) {
                beanMap.put(filter.type(), Lists.newArrayList());
            }
            filters.add(filter);
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
